package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.entity.ApUserFollow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP关注行为表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-03
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements IApFollowBehaviorService {

    @Autowired
    private IApBehaviorEntryService behaviorEntryService;


    /**
     * 保存/取消 关注行为
     *
     * @param dto
     */
    @Override
    public void followBehaviorSave(FollowBehaviorDto dto) {
        //1.根据用户ID 或者设备ID 得到用户行为实体
        ApBehaviorEntry entry = behaviorEntryService.getEntry(dto.getUserId(), dto.getEquipmentId());

        //2.新增 或者 更新关注行为
        LambdaQueryWrapper<ApFollowBehavior> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApFollowBehavior::getEntryId, entry.getId());
        queryWrapper.eq(ApFollowBehavior::getFollowId, dto.getFollowId());
        ApFollowBehavior one = this.getOne(queryWrapper);
        if (one == null) {
            //新增关注行为
            ApFollowBehavior followBehavior = new ApFollowBehavior();
            followBehavior.setEntryId(entry.getId());
            followBehavior.setFollowId(dto.getFollowId());
            followBehavior.setOperation(dto.getOperation());
            this.save(followBehavior);
        } else {
            //已有关注行为 判断入参中操作类型 跟 现有操作类型是否一致
            if (!one.getOperation().equals(dto.getOperation())) {
                LambdaUpdateWrapper<ApFollowBehavior> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(ApFollowBehavior::getEntryId, entry.getId());
                updateWrapper.eq(ApFollowBehavior::getFollowId, dto.getFollowId());
                updateWrapper.set(ApFollowBehavior::getOperation, dto.getOperation());
                this.update(updateWrapper);
            }
        }

    }
}
